import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  getCarListApi,
  createCarApi,
  updateCarApi,
  delCarApi,
  getCarShowApi,
  checkCarApi
} from "@/api/carApi";
import { usePublicHooks } from "../hooks";
export function useCar() {
  const form = reactive({
    page: 1,
    perPage: 10,
    status: null,
    keyword: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "ID",
      type: "index",
      index: indexMethod
    },
    {
      label: "所属公司",
      prop: "corp.shortName",
      formatter(row, column, cellValue) {
        if (cellValue === undefined) {
          return "园区车辆";
        } else {
          return cellValue;
        }
      }
    },
    {
      label: "车牌号",
      prop: "number"
    },
    {
      label: "类型",
      prop: "typeFormat"
    },
    {
      label: "型号",
      prop: "model"
    },
    {
      label: "品牌",
      prop: "brandFormat"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      prop: "createdAt"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];
  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.brandFormat
      }</strong>车辆吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          checkCarApi({
            vehicleId: row.vehicleId,
            status: row.status
          }).then(() => {
            message("已成功修改车辆状态", {
              type: "success"
            });
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }

  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getCarListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getCarListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getCarListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.keyword = null;
    form.status = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增"
      };
    } else {
      const { result } = await getCarShowApi({ vehicleId: row.vehicleId });
      formInline.value = {
        title: "修改",
        vehicleId: row?.vehicleId ?? "",
        corpId: result?.corpId ?? "",
        number: result?.number ?? "",
        type: result?.type ?? "",
        brand: result?.brand ?? "",
        model: result?.model ?? "",
        remarks: result?.remarks ?? "",
        status: result?.status ?? "",
        attachment: result?.attachment ?? []
      };
    }
    addDialog({
      title: `${title}车辆信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了车辆信息`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createCarApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateCarApi(curData)
                .then(() => {
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(value) {
    delCarApi({ vehicleId: value }).then(() => {
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
